package com.example.Service;

import com.example.controller.AccessTokenResp;
import com.example.controller.Constant;
import com.example.util.RedisUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class AccessTokenService {
    private static final Logger LOGGER = LoggerFactory.getLogger(AccessTokenService.class);

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private RedisUtils redisUtils;


    public  Object getAccessToken() {
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
        requestUrl = requestUrl.replace("APPID", Constant.APP_ID);
        requestUrl = requestUrl.replace("APPSECRET", Constant.APP_SECRET);
        LOGGER.error("请求AccessToken，requestUrl=={}", requestUrl);
        System.out.println("------------------");
        //获取access_token
         Object access_token  = redisUtils.get(Constant.ACCESS_TOKEN);
        //如果失效则重新去请求获取access_token
        if(access_token==null){
            AccessTokenResp accessTokenResp = restTemplate.getForObject(requestUrl, AccessTokenResp.class);
            access_token = accessTokenResp.getAccessToken();
            //存入缓存
            redisUtils.set(Constant.ACCESS_TOKEN , access_token , Constant.REDIS_TIMEOUT_1H);
        }
        LOGGER.info("access_token:{}" , access_token);
        return access_token;
    }
}
